#include "macaddress.h"

#include <stdio.h>
#include <stdlib.h>
#include <iphlpapi.h>

MacAddress::MacAddress()
{

}

/*---------------------------------------------------------
 * 函数名称： GetAddress
 * 函数功能： 获取Mac地址
 * 输入参数： 无
 * 输出参数： 无
 * 返 回 值： Mac地址的Unsigned Long形式，返回的为第一个Mac地址
 * -------------------------------------------------------*/
DWORD MacAddress::getMacAddress()
{
    DWORD MACaddress = 0;
    IP_ADAPTER_INFO AdapterInfo[16];       // Allocate information
    // for up to 16 NICs
    DWORD dwBufLen = sizeof(AdapterInfo);  // Save memory size of buffer

    DWORD dwStatus = GetAdaptersInfo(      // Call GetAdapterInfo
        AdapterInfo,                 // [out] buffer to receive data
        &dwBufLen);                  // [in] size of receive data buffer
    if(dwStatus != ERROR_SUCCESS)
    {
        return -1UL;
    }

    // current adapter info
    PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo; // Contains pointer to
    do {
        if ((MACaddress == 0)&&(!strstr(pAdapterInfo->Description, "Virtual")))
        {
            MACaddress = pAdapterInfo->Address[5] + pAdapterInfo->Address[4] * 256 +
            pAdapterInfo->Address[3] * 256 * 256 +
            pAdapterInfo->Address[2] * 256 * 256 * 256;
        }

        pAdapterInfo = pAdapterInfo->Next;    // Progress through linked list
    } while (pAdapterInfo);                    // Terminate if last adapter

    return MACaddress;
}

/*---------------------------------------------------------
 * 函数名称： PrintAddress
 * 函数功能： 打印Mac地址，为 %02X-%02X-%02X-%02X-%02X-%02X 的形式
 * 输入参数： Mac地址
 * 输出参数： 无
 * 返 回 值： 无
 * -------------------------------------------------------*/
void MacAddress::printAddress(unsigned char MACData[])
{
    printf("\nMAC Address: %02X-%02X-%02X-%02X-%02X-%02X\n",
        MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
}
